package org.homs.continuations.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.homs.continuations.jdbc.session.Session;
import org.homs.continuations.jdbc.session.SessionFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryMapper {

	protected Map<String, Object> queryForSingleRow(final String parameterizedQuery,
			final Map<String, Object> parameters) throws SQLException {

		final Map<String, Object> r = new HashMap<String, Object>();
		final String query = applyParamsToQuery(parameterizedQuery, parameters);

		final Session session = SessionFactory.getCurrentSession();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = session.getConnection().prepareStatement(query);
			rs = ps.executeQuery();

			final int columns = rs.getMetaData().getColumnCount();
			if (!rs.next()) {
				return r;
			}
			for (int columnIndex = 1; columnIndex <= columns; columnIndex++) {
				r.put(rs.getMetaData().getColumnName(columnIndex), rs.getObject(columnIndex));
			}
		} catch (final Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		}

		return r;
	}

	protected List<Map<String, Object>> queryForMultiRow(final String parameterizedQuery,
			final Map<String, Object> parameters) throws SQLException {

		final List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		final String query = applyParamsToQuery(parameterizedQuery, parameters);

		final Session session = SessionFactory.getCurrentSession();

		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = session.getConnection().prepareStatement(query);
			rs = ps.executeQuery();

			final int columns = rs.getMetaData().getColumnCount();
			while (rs.next()) {
				final Map<String, Object> m = new HashMap<String, Object>();
				for (int columnIndex = 1; columnIndex <= columns; columnIndex++) {
					m.put(rs.getMetaData().getColumnName(columnIndex), rs.getObject(columnIndex));
				}
				r.add(m);
			}
		} catch (final Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		}

		return r;
	}

	protected Object queryForScalar(final String parameterizedQuery, final Map<String, Object> parameters) {

		// TODO
		final Object r = new Object();
		@SuppressWarnings("unused")
		final String query = applyParamsToQuery(parameterizedQuery, parameters);
		return r;
	}

	protected boolean update(final String parameterizedQuery, final Map<String, Object> parameters) {
		// TODO
		return false;
	}

	private String applyParamsToQuery(final String parameterizedQuery, final Map<String, Object> parameters) {
		// TODO Auto-generated method stub
		return parameterizedQuery;
	}

}
